import {ResourceLoader} from "./js/base/ResourceLoader.js";
import {Background} from "./js/runtime/Background.js";
import {DataStore} from "./js/base/DataStore.js";
import {Director} from "./js/Director.js";
import {Land} from "./js/runtime/Land.js";
import {Bird} from "./js/player/Bird.js";
import {StartButton} from "./js/player/StartButton.js";
// import "./js/libs/weapp-adapter.js";
// import "./js/libs/symbol.js";


export class Main {
    constructor() {
        console.log("Main()");
        // this.canvas = document.getElementById('game_canvas');
        this.canvas = wx.createCanvas();
        this.ctx = this.canvas.getContext('2d');

        this.datastore = DataStore.getInstance();

        console.log("ww:" + this.canvas.width + " wh:" + this.canvas.height);
        const loader = ResourceLoader.create();
        loader.onLoaded(map => this.onResourceFirstLoaded(map))


        // let image = new Image();
        // image.src = '../res/background.png';
        //
        // image.onload = () => {
        //     this.ctx.drawImage(
        //         image, 0, 0, image.width, image.height, 0, 0, image.width, image.height
        //     )
        // }
    }

    onResourceFirstLoaded(map) {
        // console.log(map);
        this.datastore.ctx = this.ctx;
        this.datastore.canvas = this.canvas;
        this.datastore.resLoaded = map;


        this.registerEvent();

        this.init();
    }

    initSprite() {
        console.log("initSprite()");
        this.datastore.put('background', Background)
            .put('land', Land)
            .put('bird', Bird)
            .put('pencils', [])
            .put('startButton', StartButton);


    }

    init() {
        console.log("init()");
        // this.datastore.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
        this.initSprite();
        console.log("pencils len:"+ this.datastore.get('pencils').length);
        this.director = Director.getInstance();
        this.director.isGameOver = false;
        this.director.createPencil();
        this.director.run();
    }

    registerEvent() {
        wx.onTouchStart(() => {
            //屏蔽事件冒泡
            console.log("touch");
            console.log("isGameOver:"+this.director.isGameOver);
            if (this.director.isGameOver) {
                console.log("start");
                this.init();
            } else {
                this.director.birdEvent();
            }
        },this.canvas);
    }

}
